#include "match_string_from_stream.h"
#include "platformAPI.h"
#include "stdlib.h"
#include "stdio.h"

#define STR_LEN 60

struct matchString
{
    uint8_t str[STR_LEN];
    uint32_t len;
    uint32_t pos;
};

MatchString *setMatchStr(uint8_t *str)
{
    MatchString *p = NULL;
    uint8_t i;

    //printf("[%s] start to malloc MatchString p\n",__FUNCTION__);
    p = malloc(sizeof(MatchString));
    if(p == NULL)
    {
	return NULL;
    }

    p->len = strlen(str);
    p->pos = 0;
    
    //printf("[%s] p->len [%d]\n",__FUNCTION__,p->len);
    //printf("[%s] p->pos [%d]\n",__FUNCTION__,p->pos);

    for(i = 0; i < STR_LEN; i++)
    {
	if(i < p->len)
	{
	    p->str[i] = str[i];
	}
	else
	{
	    p->str[i] = 0;
	}
    }
    return p;
}


int8_t matchStrFromInput(MatchString *p,uint8_t data)
{
    if(p->len == 0 || p->str == NULL)
    {
	return -1;
    }

    if( *(p->str + p->pos) == data)
    {
	p->pos++;
	if(p->pos == p->len)
	{
	    p->pos = 0;
	    return 0;
	}
    }
    else
    {
	p->pos = 0;
    }
    return -1;
}

int8_t matchStrFromInputDebug(MatchString *p,uint8_t data)
{
    if(p->len == 0 || p->str == NULL)
    {
	return -1;
    }

    printf("[%s] data is [%d] [%c]\n",__FUNCTION__,data,data);
    if( *(p->str + p->pos) == data)
    {
	p->pos++;
	printf("[%s] pos is [%d]\n",__FUNCTION__,p->pos);
	printf("[%s] len is [%d]\n",__FUNCTION__,p->len);
	if(p->pos == p->len)
	{
	    printf("[%s] get string!!!\n",__FUNCTION__);
	    p->pos = 0;
	    return 0;
	}
    }
    else
    {
	p->pos = 0;
    }
    return -1;
}

int8_t delMatchStr(MatchString *p)
{
    uint8_t i;
    if(p == NULL)
    {
	return 0;
    }

    p->pos = 0;
    p->len = 0;

    for(i = 0; i < STR_LEN; i++)
    {
	p->str[i] = 0;
    }

    free(p);

    return 0;
}

MatchString *setMatchData(uint8_t *buf, uint32_t len)
{
    MatchString *p = NULL;
    uint8_t i;

    //printf("[%s] start to malloc MatchString p\n",__FUNCTION__);
    p = malloc(sizeof(MatchString));
    if(p == NULL)
    {
	return NULL;
    }

    p->len = len;
    p->pos = 0;
    
    //printf("[%s] p->len [%d]\n",__FUNCTION__,p->len);
    //printf("[%s] p->pos [%d]\n",__FUNCTION__,p->pos);

    for(i = 0; i < STR_LEN; i++)
    {
	if(i < p->len)
	{
	    p->str[i] = buf[i];
	}
	else
	{
	    p->str[i] = 0;
	}
    }
    return p;
}


